import router from '../router'
import store from '../store'
// import { wachtStorage } from './watchStorage'
import { GetQueryString, isIos } from '../commonTools/commonTool'
// 验证层
// 判断是否是推荐页面
router.beforeEach((to, from, next) => {
  if (to.meta.title) document.title = to.meta.title
  if (to.path === '/reg') {
    if (!sessionStorage.getItem('shareUserCode')) sessionStorage.setItem('shareUserCode', GetQueryString('shareUserCode'))
    next()
    return
  }
  let userAgent = navigator.userAgent
  pathAssign(userAgent, to)
  let pageData = getPageData()
  if (!pageData.currentUrl) {
    pageData.currentUrl = window.location.href.split('?')[0]
    sessionStorage.setItem('currentUrl', pageData.currentUrl)
  }
  if (!to.meta.requireAuth) { next(); return false }
  if (pageData.userCode) { next(); return false }
  // 判断重定向逻辑
  if (!pageData.getUserCode) {
    let currentUrls = pageData.currentUrl
    store.dispatch('getAuthRedirectUrl', { currentUrls })
      .then(res => {
        // next()
        // console.log('从定向返回的链接+++++++++++++++++', res)
        window.location.href = res
      })
  } else {
    sessionStorage.setItem('userCode', pageData.getUserCode)
    store.dispatch('getUserToken', pageData.getUserCode)
      .then(res => {
        sessionStorage.setItem('userToken', res.data.data)
        let circleId = sessionStorage.getItem('circleId')
        store.dispatch('getCircleInfo', { circleId })
          .then(res => {
            if (res.isCreate || res.isManage || res.isJoin) {
              sessionStorage.setItem('isRefresh', 1)
              next({ path: '/grouplist' })
            } else {
              sessionStorage.setItem('isRefresh', 0)
              next({ path: '/' })
            }
          })
        // next()
      })
  }
})
// 重新分配地址路由
let pathAssign = (userAgent, to) => {
  if (userAgent.includes('iPhone') || userAgent.includes('iPad')) {
    if (to.path === '/rewardrank') { sessionStorage.setItem('originUrl', location.href); return }
    if (isIos() && to.path !== location.pathname) { location.assign(to.fullPath) }
    sessionStorage.setItem('originUrl', location.href)
  }
}
// 接收页面参数  判断
let getPageData = () => {
  let pageData = {}
  // 获取页面参数
  pageData.currentUrl = sessionStorage.getItem('currentUrl')
  // 是否页面路由检测
  pageData.getShareUserCode = sessionStorage.getItem('shareUserCode')
  pageData.getCircleId = sessionStorage.getItem('circleId')
  pageData.userCode = sessionStorage.getItem('userCode')
  pageData.getUserCode = GetQueryString('code')
  if (!pageData.getCircleId) {
    pageData.getShareUserCode = GetQueryString('shareUserCode')
    pageData.getCircleId = GetQueryString('circleId')
    sessionStorage.setItem('shareUserCode', pageData.getShareUserCode)
    sessionStorage.setItem('circleId', pageData.getCircleId)
  }
  return pageData
}
